<template>
  <div class="user-profile">
    <el-upload
      class="avatar-uploader"
      action="/api/upload"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">
      <img v-if="avatar" :src="avatar" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-upload
      class="background-uploader"
      action="/api/upload"
      :show-file-list="false"
      :on-success="handleBackgroundSuccess"
      :before-upload="beforeBackgroundUpload">
      <img v-if="background" :src="background" class="background">
      <i v-else class="el-icon-plus background-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
export default {
  data() {
    return {
      avatar: '',
      background: ''
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.avatar = URL.createObjectURL(file.raw);
    },
    handleBackgroundSuccess(res, file) {
      this.background = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        this.$message.error('上传头像图片只能是图片格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },
    beforeBackgroundUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        this.$message.error('上传背景图片只能是图片格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传背景图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    }
  }
}
</script>

<style scoped>
.avatar-uploader, .background-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
}
.avatar-uploader:hover, .background-uploader:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon, .background-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar, .background {
  width: 100px;
  height: 100px;
  display: block;
}
</style> 